<?php
//4
function manage_message_list_page() {
    if(user_access('manage chat')) {
        if (user_access('view all chat_messages')) {
            @$output = drupal_render(drupal_get_form('manage_chat_all_message_list_form'));
        } else {
            @$output = drupal_render(drupal_get_form('manage_chat_message_list_form'));
        }
    }
    return $output;
}

function manage_chat_message_list_form($form, &$form_state)
{
    $form['begin_time'] = array(
        '#title' => '',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->timestamp : '2015-01-01'),
    );
    $form['end_time'] = array(
        '#title' => '',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->timestamp : ''),
    );
    $form['message_content'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '关键字'),
        '#validated' => TRUE,
    );
    $table['#markup'] = manage_chat_message_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}




function manage_chat_all_message_list_form($form, &$form_state){
    global $user;
    $user_info = _get_user_info($user->uid);
    if(user_access('manage chat')) {
        if (!user_access('view all chat_messages')) {
            $disabled = TRUE;
            $query = db_select('employee','E');
            $query->condition('E.employee_id',$user->uid,'=');
            $query->addField('E','department_id');
            $department_id = $query->execute()->fetchAll();
            $username = $user_info['name'];
        }
    }
    $form['department_list'] =department_selection($disabled,$department_id);
    $form['from_name'] = array(
        '#type' => 'textfield',
        '#default_value' => $username ? $username : '',
        '#attributes' => array('placeholder' => '姓名'),
        '#prefix' => '<div class="agent-search-form">',
        '#validated' => TRUE,
    );
    $form['to_name'] = array(
        '#type' => 'textfield',
        '#default_value' =>'',
        '#attributes' => array('placeholder' => '姓名'),
        '#validated' => TRUE,
    );
    $form['begin_time'] = array(
        '#title' => '',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->timestamp : '2015-01-01'),
    );
    $form['end_time'] = array(
        '#title' => '',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->timestamp : ''),
    );
    $form['message_content'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '关键字'),
        '#validated' => TRUE,
        '#suffix' =>'</div>',
    );
    $table['#markup'] =manage_chat_message_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}




function manage_chat_message_view_page($form, $form_state){
    global $user;
    $output = '';
    $header = array(
        array('data' => '发送者', 'class' => ['sender']),
        array('data' => '聊天内容', 'class' => ['content1']),
        array('data' => '发送时间', 'class'=>['timestamp']),
    );
    $rows = array();
    $chat_id = $_GET['chat_id'] ? $_GET['chat_id'] : $form_state['values']['chat_id'];
    $query = db_select('chat_messages', 'CM')->extend('PagerDefault')->extend('TableSort');
    $query->leftjoin('chat_users', 'CU', 'CM.sender_id = CU.user_id And CM.chat_id = CU.chat_id');
    $query->fields('CM');
    $query->addField('CU','nickname');

    //  名字查询条件
    if(!empty($form_state['values']['from_name']) && !empty($form_state['values']['to_name'])) {
        $chat_id = _get_chat_id_by_name($form_state['values']['from_name'],$form_state['values']['to_name']);
        $query->condition('CM.chat_id',$chat_id, '=');
    }
    //  关键字查询条件
    if(!empty($form_state['values']['message_content'])){
        $query->condition('CM.content', '%' . db_like($form_state['values']['message_content']) . '%', 'LIKE');
    }
    //  时间查询条件
    if(!empty($form_state['values']['begin_time'])){
        $time = strtotime($form_state['values']['begin_time']['year'].'-'.$form_state['values']['begin_time']['month'].'-'.$form_state['values']['begin_time']['day'])*1000;
        $query->condition('CM.timestamp',$time, '>=');
    }
    if(!empty($form_state['values']['end_time'])){
        $time1 = strtotime($form_state['values']['end_time']['year'].'-'.$form_state['values']['end_time']['month'].'-'.$form_state['values']['end_time']['day']+1)*1000;
        $query->condition('CM.timestamp',$time1, '<=');
    }
    //  部门查询条件
    if(!empty($form_state['values']['department'])){
       $user_ids = _department_get_user_id($form_state['values']['department']);
       if($user_ids){
            $query->condition('CU.user_id',$user_ids,'in');
       }
    }
    if(user_access('manage chat') && ! user_access('view all chat_messages')){
        $chat_id = get_chat_id_by_user_id($user->uid);
        if(!empty($chat_id)){
            $query->condition('CM.chat_id',$chat_id,'in');
        }
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();
    $n = 1;
    foreach ($result as $row) {
        if($row->sender_id == $user->uid){
            $nickname = '自己';
        }else{
            $nickname = $row->nickname;
        }
        if($row->timestamp){
            $timestamp = date('Y-m-d H:i:s',$row->timestamp/1000);
        }
        $rows[] = array(
            array('data' => $nickname, 'class' => ['essential employee_name '.$row->nickname]),
            array('data' => $row->content, 'class' => ['essential employee_name '.$row->content]),
            array('data' => $timestamp, 'class' => ['essential employee_name '.$timestamp]),
        );
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover'))));
    $output .= theme('pager');
    return $output;
}

function _get_chat_id_by_name($from_name,$to_name){
    // get from_id
    $query = db_select('chat_users','CU');
    $query->condition('CU.nickname',$from_name,'=');
    $query->addField('CU','user_id');
    $from_ids = $query->execute()->fetchAll();
    foreach ( $from_ids as $key => $value ) {
        $from_id = $value->user_id;
    }

    // get to_id
    $query = db_select('chat_users','CU');
    $query->condition('CU.nickname',$to_name,'=');
    $query->addField('CU','user_id');
    $to_ids = $query->execute()->fetchAll();
    foreach ($to_ids as $key => $value ) {
        $to_id = $value->user_id;
    }

    // get chat_id
    $query = db_select('chat','C');
    $or = db_or()->condition('C.title', $from_id.'&'.$to_id, '=')->condition('C.title', $to_id.'&'.$from_id, '=');
    $query->condition($or);
    $query->addField('C','chat_id');
    $results = $query->execute()->fetchAll();
    foreach($results as $key => $value){
        $chat_id= $value->chat_id;
    }
    return $chat_id;
}

function _department_get_user_id($department_id){
    // get department member
    $query = db_select('employee','E');
    $query->condition('E.department_id',$department_id,'=');
    $query->addField('E','employee_id');
    $results = $query->execute()->fetchAll();
    foreach ($results as $key => $value ) {
        $result[$value->employee_id] = $value->employee_id;
    }
    return $result;
}

function get_chat_id_by_user_id($uid){
    $res = db_query('SELECT DISTINCT(chat_id) as chat_id FROM chat_users WHERE user_id = '.$uid)->fetchAll();
    foreach($res as $k => $v){
        $chat_id[] = $v->chat_id;
    }
    return $chat_id;
}